package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * Url图片上传
 * @author xiaodi
 * @date 2025/4/11
 * @Description
 */
@Service
public class UrlPictureUpload extends PictureUploadTemplate {
    private static final long ONE_M = 1024 * 1024L;
    private static final List<String> ALLOW_FORMAT_LIST = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");

    @Override
    protected String getOriginalFilename(Object inputSource) {
        String fileUrl=(String) inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        try {
            // 1. 验证 URL 格式  验证是否是合法的 URL
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }
        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://")&&!fileUrl.startsWith("https://"),
                ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");
        // 3. 发送 HEAD 请求以验证文件是否存在
         HttpResponse httpResponse=null;
               try {
                   httpResponse= HttpUtil.createRequest(Method.HEAD,fileUrl).execute();
                   //未正常返回，无需执行其他判断
                   if(httpResponse.getStatus()!=HttpStatus.HTTP_OK){
                       return;
                   }
                   // 4. 校验文件类型
                   String contentType = httpResponse.header("Content-Type");
                   if (StrUtil.isNotBlank(contentType)) {
                       ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(contentType.toLowerCase()),
                               ErrorCode.PARAMS_ERROR, "文件类型错误");
                   }
                   //5、校验文件大小
                   String contentLengthStr=httpResponse.header("Content-Length");
                   if (StrUtil.isNotBlank(contentLengthStr)){
                       try {
                           long contentLength = Long.parseLong(contentLengthStr);
                           ThrowUtils.throwIf(contentLength > 2*ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                       }catch (NumberFormatException e){
                           throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                       }

                   }
               } finally {
                   //释放资源
                   if (httpResponse!=null){
                       httpResponse.close();
                   }
               }

        }


    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        String fileUrl=(String) inputSource;
        //下载文件到临时文件
        HttpUtil.downloadFile(fileUrl, file);
    }
}
